# -*- encoding: utf-8 -*-
import time
import wizard
import netsvc
import pooler
from osv import fields, osv
from tools.translate import _
from osv.orm import browse_record, browse_null
import datetime


#
#class aas_show_my_personal_timetable_line_wizard(wizard.interface):
#	def _aas_show_my_personal_timetable_line(self, cr, uid, data, context):
#		pool = pooler.get_pool(cr.dbname)
#		if not context:
#			context = {}
#		year_obj = pool.get('aas.academic.year')
#		view_id = year_obj.get_view_id(cr, uid, 'aas_timetable', 'aas_timetable_line_tree_view', context=context)
#		#TODO: get correct lines_ids 
#		lines_ids = [1,2]
#		result = {
#			'domain': "[('id', 'in', [%s])]" % (','.join(map(str, lines_ids))),
#	        'view_type': 'form',
#	        'view_mode': 'tree,form',
#		    'src_model': 'aas.timetable.line',
#	        'res_model': 'aas.timetable.line',
#	        'view_id': [view_id],
#	        'search_view_id': [],
#	        'type': 'ir.actions.act_window',
#		}
#		return result
#
#	states = {
#		'init': {
#			'actions': [],
#			'result': {'type': 'action', 'action': _aas_show_my_personal_timetable_line, 'state': 'end'}
#		}
#	}	
#aas_show_my_personal_timetable_line_wizard("aas.show.my.personal.timetable.line")


#===============================================================================
# class aas_show_my_session_timetable_line_wizard(wizard.interface):
#	def _aas_show_my_session_timetable_line(self, cr, uid, data, context):
#		pool = pooler.get_pool(cr.dbname)
#		if not context:
#			context = {}
#		year_obj = pool.get('aas.academic.year')
#		view_id = year_obj.get_view_id(cr, uid, 'aas_timetable', 'aas_timetable_line_tree_view', context=context)
#		#TODO: get correct lines_ids 
#		lines_ids = [1,2]
#		result = {
#			'domain': "[('id', 'in', [%s])]" % (','.join(map(str, lines_ids))),
#	        'view_type': 'form',
#	        'view_mode': 'tree,form',
#		    'src_model': 'aas.timetable.line',
#	        'res_model': 'aas.timetable.line',
#	        'view_id': [view_id],
#	        'search_view_id': [],
#	        'type': 'ir.actions.act_window',
#		}
#		return result
# 
#	states = {
#		'init': {
#			'actions': [],
#			'result': {'type': 'action', 'action': _aas_show_my_session_timetable_line, 'state': 'end'}
#		}
#	}	
# aas_show_my_session_timetable_line_wizard("aas.show.my.session.timetable.line")
#===============================================================================


#===============================================================================
# class aas_show_my_personal_exam_schedule_line_wizard(wizard.interface):
#	def aas_show_my_personal_exam_schedule_line(self, cr, uid, data, context):
#		pool = pooler.get_pool(cr.dbname)
#		if not context:
#			context = {}
#		year_obj = pool.get('aas.academic.year')
#		view_id = year_obj.get_view_id(cr, uid, 'aas_timetable', 'aas_exam_schedule_line_tree_view', context=context)
#		#TODO: get correct lines_ids 
#		lines_ids = [1,2]
#		result = {
#			'name': 'My Personal Exam Schedule',
#			'domain': "[('id', 'in', [%s])]" % (','.join(map(str, lines_ids))),
#	        'view_type': 'form',
#	        'view_mode': 'tree,form',
#		    'src_model': 'aas.exam.schedule.line',
#	        'res_model': 'aas.exam.schedule.line',
#	        'view_id': [view_id],
#	        'search_view_id': [],
#	        'type': 'ir.actions.act_window',
#		}
#		return result
# 
#	states = {
#		'init': {
#			'actions': [],
#			'result': {'type': 'action', 'action': aas_show_my_personal_exam_schedule_line, 'state': 'end'}
#		}
#	}	
# aas_show_my_personal_exam_schedule_line_wizard("aas.show.my.personal.exam.schedule.line")
#===============================================================================


#===============================================================================
# class aas_show_my_session_exam_schedule_line_wizard(wizard.interface):
#	def aas_show_my_session_exam_schedule_line(self, cr, uid, data, context):
#		pool = pooler.get_pool(cr.dbname)
#		if not context:
#			context = {}
#		year_obj = pool.get('aas.academic.year')
#		view_id = year_obj.get_view_id(cr, uid, 'aas_timetable', 'aas_exam_schedule_line_tree_view', context=context)
#		#TODO: get correct lines_ids 
#		lines_ids = [1,2]
#		result = {
#			'name': 'My Session Exam Schedule',
#			'domain': "[('id', 'in', [%s])]" % (','.join(map(str, lines_ids))),
#	        'view_type': 'form',
#	        'view_mode': 'tree,form',
#		    'src_model': 'aas.exam.schedule.line',
#	        'res_model': 'aas.exam.schedule.line',
#	        'view_id': [view_id],
#	        'search_view_id': [],
#	        'type': 'ir.actions.act_window',
#		}
#		return result
# 
#	states = {
#		'init': {
#			'actions': [],
#			'result': {'type': 'action', 'action': aas_show_my_session_exam_schedule_line, 'state': 'end'}
#		}
#	}	
# aas_show_my_session_exam_schedule_line_wizard("aas.show.my.session.exam.schedule.line")
#===============================================================================


class aas_my_personal_information_wizard(wizard.interface):
	
	_form_template = '''
		<form string="%s">
			<separator string="Basic Information" colspan="4"/>
			<field name="code" colspan="2"/>
    		<field name="name" colspan="2"/>
    		<newline/>
    		<field name="gender" colspan="2"/>
    		<field name="date_birth" colspan="2"/>
    		<newline/>
    		<field name="gov_id" colspan="2"/>
			<field name="country_id" colspan="2"/>
			<newline/>
    		<field name="tax_code" colspan="2"/>
    		<newline/>
    		<field name="perm_addr" colspan="4"/>
    		<newline/>
    		<separator string="Additional Information" colspan="4"/>
			<field name="tel" colspan="2"/>
    		<field name="mobile" colspan="2"/>
    		<newline/>
    		<field name="email" colspan="2"/>
    		<field name="fax" colspan="2"/>
    		<newline/>
    		<field name="cur_addr" colspan="4"/>
    		<newline/>
    		<separator string="Configuration" colspan="4"/>
			<field name="show_more_info" colspan="2"/>
			<field name="receive_emails" colspan="2"/>
			<newline/>
    	</form>
	'''
	_form = _form_template % (_('My Personal Information'),)
	
	_fields = {
		'code': {'type': 'char', 'string': _('Code'), 'size': 64, 'readonly': True},
		'name': {'type': 'char', 'string': _('Full Name'), 'size': 64, 'readonly': True},
		'gender': {'type': 'selection', 'selection': [('male', _('Male')), ('female', _('Female'))], 'string': _('Gender'), 'size': 64, 'readonly': True},
		'date_birth': {'type': 'date', 'string': _('Date of Birth'), 'readonly': True},
		'gov_id': {'type': 'char', 'string': _('Goverment ID'), 'size': 64, 'readonly': True},
		'cur_addr': {'type': 'char', 'string': _('Current Address'), 'size': 128},
		'perm_addr': {'type': 'char', 'string': _('Permanent Address'), 'size': 128, 'readonly': True},
		'tel': {'type': 'char', 'string': _('Telephone Number'), 'size': 64},
		'mobile': {'type': 'char', 'string': _('Mobile Number'), 'size': 64},
		'email': {'type': 'char', 'string': _('Email Address'), 'size': 64},
		'fax': {'type': 'char', 'string': _('Fax Number'), 'size': 64},
		'tax_code': {'type': 'char', 'string': _('Tax Code'), 'size': 64, 'readonly': True},
		'country_id': {'type': 'many2one', 'relation': 'res.country', 'readonly': True, 'string': _('Country')},
		'show_more_info': {'type': 'boolean', 'string': _('Show Additional Information To Others')},
		'receive_emails': {'type': 'boolean', 'string': _('Receive Email Notifications')},
	}
	
	def _init(self, cr, uid, data, context):
		res = {}
		if not context:
			context = {}
		pool = pooler.get_pool(cr.dbname)
		user_obj = pool.get('res.users')
		user = user_obj.browse(cr, uid, uid, context=context)
		_fields = self._fields
		for field in _fields:
			if hasattr(user, field):
				if _fields[field]['type'] == 'many2one':
					res.update({field: getattr(getattr(user, field), 'id')})
				else: res.update({field: getattr(user, field)})
		return res
	
	def _set_personal_information(self, cr, uid, data, context):
		if not context:
			context = {}
		pool = pooler.get_pool(cr.dbname)
		user_obj = pool.get('res.users')
		keys = ['tel', 'mobile', 'email', 'fax', 'cur_addr', 'show_more_info', 'receive_emails']
		vals = {}
		for key in keys:
			vals.update({key: data['form'][key]})
		user_obj.write(cr, 1, [uid], vals, context=context)
		return {}
   
	states = {
		'init': {
			'actions': [_init],
			'result': {'type': 'form', 'arch': _form, 'fields': _fields, 'state': [('set', _('Set'), 'gtk-ok', True),]},
		},
		'set': {
			'actions': [_set_personal_information],
			'result': {'type': 'state', 'state': 'init'},
		},
	}	
aas_my_personal_information_wizard("aas.my.personal.information")


def get_all_registered_courses(cr, uid, student_id, personal=True, context=None):
	pool = pooler.get_pool(cr.dbname)
	course_obj = pool.get('aas.course.course')
	course_student_obj = pool.get('aas.course.student')
	res = []
	if personal:
		registers_ids = course_student_obj.search(cr, uid, [('course_id.is_in_current_academic_state', '=', 1), 
														('student_id', '=', student_id),
														('course_id.state', 'not in', ('draft', 'canceled', 'confirmed', 'refused'))], context=context)
		if registers_ids:
			sql = '''
				SELECT course_id
				FROM aas_course_student
				WHERE id in %s
			'''
			cr.execute(sql, (tuple(registers_ids + [-1, -1]),))
			if cr.rowcount > 0:
				courses_ids = [id for (id,) in cr.fetchall()]
				res = list(set(courses_ids))
	else:
		courses_ids = course_obj.search(cr, uid, [('is_in_current_academic_state', '=', 1),
												('state', 'not in', ('draft', 'canceled', 'confirmed', 'refused'))], context=context)
		res = list(set(courses_ids))
	return res


class aas_show_my_personal_timetable_line_wizard(wizard.interface):
	
	_form_template = '''
		<form string="%s">
			<field name="timetable_lines" colspan="4" nolabel="1" widget="one2many_list"/>
    	</form>
	'''
	_form = _form_template % (_('My Personal Timetable'),)
	
	_fields = {
		'timetable_lines': {'type': 'many2many', 'string': '', 'relation': 'aas.course.course', 'readonly': True},
	}
	
	def _init(self, cr, uid, data, context):
		res = {}
		if not context:
			context = {}
		courses_ids = get_all_registered_courses(cr, uid, uid, context=context)
		res['timetable_lines'] = courses_ids
		return res
   	
   	def print_report(self, cr, uid, data, context):
		datas = {}
		datas['model'] = 'aas.course.list'
		
		pool = pooler.get_pool(cr.dbname)
		
		datas['id'] = 1
		datas['ids'] = [1]
		datas['context'] = {}
		return {'type': 'ir.actions.report.xml', 'report_name': 'aas_timetable_report', 'datas': datas}
	
	states = {
		'init': {
			'actions': [_init],
			'result': {'type': 'form', 'arch': _form, 'fields': _fields, 'state': []},
		},
		'print': {
			'actions': [],
			'result': {'type': 'action', 'action': print_report, 'state': 'end'},
		},
	}	
aas_show_my_personal_timetable_line_wizard("aas.show.my.personal.timetable.line")






class aas_show_my_session_timetable_line_wizard(wizard.interface):
	
	_form_template = '''
		<form string="%s">
			<field name="timetable_lines" colspan="4" nolabel="1" widget="one2many_list"/>
    	</form>
	'''
	_form = _form_template % (_('My Session Timetable'),)
	
	_fields = {
		'timetable_lines': {'type': 'many2many', 'string': '', 'relation': 'aas.course.course', 'readonly': True},
	}
	
	def _init(self, cr, uid, data, context):
		res = {}
		if not context:
			context = {}
		
		courses_ids = get_all_registered_courses(cr, uid, uid, personal=False, context=context)
		self.list_id = False
		if courses_ids:
			sql = '''
				SELECT list_id
				FROM aas_course_course
				WHERE id = %s
			'''
			cr.execute(sql, (courses_ids[0],))
			if cr.rowcount > 0:
				self.list_id = cr.fetchone()[0]
		res['timetable_lines'] = courses_ids
		return res

	def print_report(self, cr, uid, data, context):
		datas = {}
		datas['model'] = 'aas.course.list'
		
		if self.list_id:
			datas['id'] = self.list_id
			datas['ids'] = [self.list_id]
		else:
			datas['id'] = False
			datas['ids'] = []
		datas['context'] = {}
		return {'type': 'ir.actions.report.xml', 'report_name': 'aas_timetable_report', 'datas': datas}
	   
	states = {
		'init': {
			'actions': [_init],
			'result': {'type': 'form', 'arch': _form, 'fields': _fields, 'state': [('print', _('Download'), 'gtk-print', True)]},
		},
		'print': {
			'actions': [],
			'result': {'type': 'action', 'action': print_report, 'state': 'end'},
		},
	}	
aas_show_my_session_timetable_line_wizard("aas.show.my.session.timetable.line")


class aas_show_my_personal_exam_schedule_line_wizard(wizard.interface):
	
	_form_template = '''
		<form string="%s">
			<field name="exam_schedule_lines" colspan="4" nolabel="1" widget="one2many_list" context="{'exam_mode':1}"/>
    	</form>
	'''
	_form = _form_template % (_('My Personal Exam Schedule'),)
	
	_fields = {
		'exam_schedule_lines': {'type': 'many2many', 'string': '', 'relation': 'aas.course.course', 'readonly': True},
	}
	
	def _init(self, cr, uid, data, context):
		res = {}
		if not context:
			context = {}
		courses_ids = get_all_registered_courses(cr, uid, uid, personal=True, context=context)
		res['exam_schedule_lines'] = courses_ids
		return res
   
	states = {
		'init': {
			'actions': [_init],
			'result': {'type': 'form', 'arch': _form, 'fields': _fields, 'state': []},
		},
	}	
aas_show_my_personal_exam_schedule_line_wizard("aas.show.my.personal.exam.schedule.line")

class aas_show_my_session_exam_schedule_line_wizard(wizard.interface):
	
	_form_template = '''
		<form string="%s">
			<field name="exam_schedule_lines" colspan="4" nolabel="1" widget="one2many_list" context="{'exam_mode':1}"/>
    	</form>
	'''
	_form = _form_template % (_('My Session Exam Schedule'),)
	
	_fields = {
		'exam_schedule_lines': {'type': 'many2many', 'string': '', 'relation': 'aas.course.course', 'readonly': True},
	}
	
	def _init(self, cr, uid, data, context):
		res = {}
		if not context:
			context = {}
		courses_ids = get_all_registered_courses(cr, uid, uid, personal=False, context=context)
		self.list_id = False
		if courses_ids:
			sql = '''
				SELECT list_id
				FROM aas_course_course
				WHERE id = %s
			'''
			cr.execute(sql, (courses_ids[0],))
			if cr.rowcount > 0:
				self.list_id = cr.fetchone()[0]
		res['exam_schedule_lines'] = courses_ids
		return res
   
	def print_report(self, cr, uid, data, context):
		datas = {}
		datas['model'] = 'aas.course.list'
		
		if self.list_id:
			datas['id'] = self.list_id
			datas['ids'] = [self.list_id]
		else:
			datas['id'] = False
			datas['ids'] = []
		datas['context'] = {}
		return {'type': 'ir.actions.report.xml', 'report_name': 'aas_exam_schedule_report', 'datas': datas}
	
	states = {
		'init': {
			'actions': [_init],
			'result': {'type': 'form', 'arch': _form, 'fields': _fields, 'state': [('print', _('Download'), 'gtk-print', True)]},
		},
		'print': {
			'actions': [],
			'result': {'type': 'action', 'action': print_report, 'state': 'end'},
		},
	}	
aas_show_my_session_exam_schedule_line_wizard("aas.show.my.session.exam.schedule.line")


class aas_personal_enrollment_wizard(wizard.interface):
	
	_form_template = '''
		<form string="%s">
			<field name="courses_registered" colspan="4" nolabel="1" widget="one2many_list" context="{'register_mode':1}"/>
    	</form>
	'''
	_form = _form_template % (_('My Personal Enrollment'),)
	
	_fields = {
		'courses_registered': {'type': 'many2many', 'string': '', 'relation': 'aas.course.student', 'readonly': True},
	}
	
	def _init(self, cr, uid, data, context):
		res = {}
		if not context:
			context = {}
		
		pool = pooler.get_pool(cr.dbname)
		course_obj = pool.get('aas.course.course')
		course_student_obj = pool.get('aas.course.student')
		self.registers_ids = course_student_obj.search(cr, uid, [('course_id.is_in_current_academic_state', '=', 1), 
														('student_id', '=', uid),
														('course_id.state', 'not in', ('draft', 'canceled', 'confirmed', 'refused'))], context=context)

		self.list_id = False
		 
		if self.registers_ids:
			sql = '''
				SELECT list_id
				FROM aas_course_course
				WHERE id IN (
					SELECT course_id
					FROM aas_course_student
					WHERE id = %s
				)
			'''
			cr.execute(sql, (self.registers_ids[0],))
			if cr.rowcount > 0:
				self.list_id = cr.fetchone()[0]
		res['courses_registered'] = self.registers_ids
		return res
   
	def print_report(self, cr, uid, data, context):
		datas = {}
		datas['model'] = 'res.users'
		
		if not self.registers_ids:
			raise osv.except_osv(_('Error!'), _('Enrollment report is not available!'))
		
		datas['context'] = {'student_id': uid, 'registers_ids': self.registers_ids}
		return {'type': 'ir.actions.report.xml', 'report_name': 'aas_enrollment_report', 'datas': datas}
	
	states = {
		'init': {
			'actions': [_init],
			'result': {'type': 'form', 'arch': _form, 'fields': _fields, 'state': [('print', _('Download'), 'gtk-print', True)]},
		},
		'print': {
			'actions': [],
			'result': {'type': 'action', 'action': print_report, 'state': 'end'},
		},
	}	
aas_personal_enrollment_wizard("aas.personal.enrollment")